<?php

class DB implements InterfaceDB {
    static private $instance = null;
    private $_bd;
    const DB_HOST = "localhost";
    const DB_USER = "root";
    const DB_PASS = "";
    const DB_NAME = "mycms";

    private function __construct() {
        $this->_db = new mysqli(self::DB_HOST,self::DB_USER,self::DB_PASS,self::DB_NAME);
        $this->_db->set_charset('utf8');
    }
    private function __clone() {}

    static function getInstance() {
        if (is_null(self::$instance))
            self::$instance = new DB;
        return self::$instance;
    }

    function getSiteData() {
        $query = "SELECT name,head_text,footer_text,theme,logo_path
                  FROM site";
        $result = $this->_db->query($query);
        if (!$result) return FALSE;
        return $result->fetch_assoc();
    }
    function getPagesData($id_cat='') {
        $where = "";
        if (!empty($id_cat)) $where = "WHERE id_category = ".$id_cat;

        $query = "SELECT id,text,id_category
                  FROM pages ".$where;

        $result = $this->_db->query($query);

        if (!$result) return FALSE;

        return $this->db2array($result);
    }

    function getPage($id_pages) {
        if (!empty($id_pages)) {
            $query = "SELECT id,text,id_category
                  FROM pages WHERE id = {$id_pages}";

            $result = $this->_db->query($query);

            if (!$result) return FALSE;

            return $this->db2array($result);
        }
    }

    function getAllCategory() {
        $query = "SELECT id,description,name
                  FROM category";
        $result = $this->_db->query($query);

        if (!$result) return FALSE;

        return $this->db2array($result);
    }

    protected function db2array($data) {
        $resultData = array();

        while ($row = $data->fetch_assoc()) {
            $resultData[] = $row;
        }

        return $resultData;
    }

    function addPage($text,$cat_id) {

    }

    function addCat($text,$desc) {

    }

    function updateSiteData($arr) {
        $query = "UPDATE site SET ";
        foreach ($arr as $k => $v) {
            $query .= $k." = '".$v."'";
        }

        $result = $this->_db->query($query);
        if (!$result) return FALSE;
        return TRUE;
    }
}